package com.ctrip.study.algorithm.stack;

import org.junit.Test;

import junit.framework.TestCase;

/**
 * 分隔符匹配（括号匹配）.
 */
public class Bracket extends TestCase {

	public static boolean bracket(String input) {
		MyArrayStack<Character> stack = new MyArrayStack<>(input.length());
		for (int i = 0; i < input.length(); i++) {
			Character c = input.charAt(i);
			switch (c) {
			case '{':
			case '[':
			case '(':
				stack.push(c);
				break;
			case '}':
			case ']':
			case ')':
				Character data = stack.pop();	
				if((c == '}' && data != '{') || (c == ']' && data != '[') || (c == ')' && data != '(')){
					System.out.println("Error in " + c);
					return false;
				}
				break;
			default:
				break;
			}
		}
		if(!stack.isEmpty()){
			return false;
		}
		return true;
	}

	@Test
	public void test() {
		String input = "a[d]";
		assertEquals(true, Bracket.bracket(input));
		input = "a[b{c}d]e";
		assertEquals(true, Bracket.bracket(input));
		input = "a[b(c}d]e";
		assertEquals(false, Bracket.bracket(input));
		input = "a{b{c}d]e}";
		assertEquals(false, Bracket.bracket(input));
		input = "a{b(c)";
		assertEquals(false, Bracket.bracket(input));
	}

}
